package com.vooda.controller;

import com.vooda.dto.vo.BaseResult;
import com.vooda.service.VerifyCodeService;
import com.vooda.util.ImageCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * 验证码controller
 *
 * @author charlee
 * @date 2017/12/8
 */

@ApiIgnore
@Api(description = "短信/邮件/图形验证码")
@RestController
@RequestMapping("/verifyCode")
@Scope("prototype")
public class VerifyCodeController {

    @Autowired
    private VerifyCodeService verifyCodeService;

    @ApiOperation(value = "获取短信/邮箱验证码", notes = "获取短信验证码需传递codeType参数，否则发送通用验证码")
    @GetMapping("/gen")
    public BaseResult getVerifyCode(@ApiParam(value = "手机号/邮箱", required = true) @RequestParam String account,
                                    @ApiParam(value = "短信模板类型 1通用 2注册 3找回密码") @RequestParam(required = false) Integer codeType) {
        return verifyCodeService.sendVerifyCode(account, codeType);
    }

    @ApiOperation(value = "获取图形验证码")
    @GetMapping(value = "/imageCode")
    public String getImageVerifyCode(@ApiParam(value = "随机数", required = true) @RequestParam String randomCode, HttpServletResponse response) {
        try {
            OutputStream os = response.getOutputStream();
            Map<String, Object> map = ImageCode.getImageCode(60, 20, os);
            String code = map.get("strEnsure").toString().toLowerCase();
            verifyCodeService.saveImageVerifyCode(randomCode, code);
            ImageIO.write((BufferedImage) map.get("image"), "JPEG", os);
        } catch (IOException e) {
            return "";
        }
        return null;
    }
}
